package com.demo.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.demo.pojo.EntityPage;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class CommonUtil {

    private static final double EARTH_RADIUS = 6371.0;

    private CommonUtil() {
        throw new IllegalStateException("CommonUtil class");
    }

    public static String utf8Str(byte[] obj) {
        int negativeSignNum = 0;
        for (byte b : obj) {
            if (b < 0) {
                negativeSignNum++;
            }
        }
        if (negativeSignNum == obj.length) {
            return null;
        }
        String str = StrUtil.utf8Str(obj);
        // 查找\u0000的位置
        int index = str.indexOf("\u0000");
        // 如果找到了\u0000，则截取该位置之前的字符串，否则返回原始字符串
        return (index != -1) ? str.substring(0, index) : str;
    }

    public static Double checkDouble(Double target){
        if (target == Double.MAX_VALUE){
            return null;
        }else {
            return target;
        }
    }

    public static Integer checkInteger(Integer target){
        if (target == Integer.MAX_VALUE){
            return null;
        }else {
            return target;
        }
    }

    public static Boolean checkBool(Integer target){
        return target == 1;
    }

    public static Double coverDouble2Structure(Double target){
        if (target == null){
            return Double.MAX_VALUE;
        }else {
            return target;
        }
    }

    public static Integer coverInteger2Structure(Integer target){
        if (target == null){
            return Integer.MAX_VALUE;
        }else {
            return target;
        }
    }

    public static String convertToDM(double coordinate, boolean isLongitude) {
        String direction;
        int degrees = (int) Math.abs(coordinate);
        double minutes = (Math.abs(coordinate) - degrees) * 60;
        if (isLongitude) {
            direction = coordinate < 0 ? "W" : "E";
        } else {
            direction = coordinate < 0 ? "S" : "N";
        }
        return String.format("%d°%.3f'%s", degrees, minutes, direction);
    }

    public static Date parseDateStr(String dateStr){
        if (NumberUtil.isLong(dateStr)){
            return DateUtil.date(Long.parseLong(dateStr) * 1000);
        }else {
            return DateUtil.parse(dateStr);
        }
    }

    /**
     * 根据泛型，返回空分页值
     * @return
     * @param <T>
     */
    public static <T> EntityPage<List<T>> defaultEntityPageForPrototype(){
        EntityPage<List<T>> entityPage = new EntityPage<>();
        entityPage.setData(new ArrayList<>());
        entityPage.setTotal(0L);
        return entityPage;
    }
}
